/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ru.example.netcracker.model;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import ru.example.netcracker.FileSettings;
import ru.example.netcracker.model.entity.Alarm;
import ru.example.netcracker.model.entity.Notification;
import ru.example.netcracker.model.entity.TaskGroup;

/**
 *
 * @author Nikolay
 */
public class XMLProvider implements TaskProvider {

    private static final Logger LOG = Logger.getLogger(XMLProvider.class.getName()); 
    
    @Override
    public Scheduler loadTasks() {
        LOG.log(Level.INFO, "loadTasks from XML");
        FileSettings settings = FileSettings.getInstance();
        File taskFile = settings.getTaskFile();
        try (InputStream is = new FileInputStream(taskFile)) {
            JAXBContext jaxb = JAXBContext.newInstance(TaskGroup.class, Alarm.class, Notification.class);
            Unmarshaller unmarsh = jaxb.createUnmarshaller();
            Scheduler sch = (Scheduler) unmarsh.unmarshal(is);
            LOG.log(Level.DEBUG, "loaded tasks from XML: " + sch);
            return sch;
        } catch (FileNotFoundException ex) {
            LOG.log(Level.ERROR, "Exception: ", ex);
            return new TaskGroup();
        } catch (IOException | JAXBException ex) {
            LOG.log(Level.ERROR, "Exception: ", ex);
            return new TaskGroup();
        }
    }

    @Override
    public void saveTasks(Scheduler sch) {
        LOG.log(Level.INFO, "saveTasks to XML");
        FileSettings settings = FileSettings.getInstance();
        File taskFile = settings.getTaskFile();
        try (OutputStream os = new FileOutputStream(taskFile)) {
            JAXBContext jaxb = JAXBContext.newInstance(TaskGroup.class, Alarm.class, Notification.class);
            Marshaller marsh = jaxb.createMarshaller();
            marsh.marshal(new TaskGroup(sch), os);
            LOG.log(Level.DEBUG, "saved tasks to XML: " + sch);
        } catch (FileNotFoundException ex) {
            LOG.log(Level.ERROR, "Exception: ", ex);
        } catch (IOException | JAXBException ex) {
            LOG.log(Level.ERROR, "Exception: ", ex);
        }
    }
    
}
